//app.js
const CusBase64 = require('utils/base64.js')
const hostUrl = 'https://api.st365.vip/' 
// const hostUrl = 'https://testapi.st365.vip/'
// const hostUrl = 'http://192.168.1.141:8080/'
App({
  onLaunch: function () {
    wx.showLoading({
      title: '加载中',
    })
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // console.log(res)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    //       wx.getUserInfo({
    //         success: res => {
    //           // 可以将 res 发送给后台解码出 unionId
    //           this.globalData.userInfo = res.userInfo

    //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //           // 所以此处加入 callback 以防止这种情况
    //           if (this.userInfoReadyCallback) {
    //             this.userInfoReadyCallback(res)
    //           }
    //         }
    //       })
    //     }
    //   }
    // })
    //获取本地存储用户名密码
    var username = wx.getStorageSync('username')
    var password = wx.getStorageSync('password')    
    let _self = this
    if (username && password){
      this.getToken(username, password)      
    }else{
      wx.hideLoading()
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  getToken: function (name, password){   
    let base64 = CusBase64.CusBASE64.encoder('stationaryterminal:e3b3e9220ed64d199eacc25788b8a84d')
    let _self = this
    wx.request({
      url: 'https://login.st365.vip/oauth/token?grant_type=password&username=' + name +'&password=' + password,
      // url: 'http://192.168.1.141:8000/oauth/token?grant_type=password&username=ltadmin&password=aaaa1111',
      method: 'POST',
      header: { "Authorization": "Basic " + base64},
      success: function (res) {        
        if(res.data.error){
          console.log(res.data)
          wx.showToast({
            title: res.data.error_description,
            icon:'none'
          })
        }else{
          wx.showLoading({
            title: '加载中'
          })
          _self.globalData.tokenId = res.data.access_token
          // console.log(_self.globalData.tokenId) 
          _self.login() 
        }                               
      },
      error: function (xhr, type, status) {
        console.log(type)
      }
    })
  },
  login: function (successCallback){
    let _self = this
    wx.request({
      url: hostUrl + 'client/employees/info',
      method: 'POST',
      header: { "Authorization": "Bearer " + this.globalData.tokenId },
      success: function (res) {
        let data = res.data.data        
        if(data.companyList.length === 0){
          _self.globalData.companys.push(data.company)
        }else{
          _self.globalData.companys = data.companyList
        }
        wx.hideLoading()
        wx.redirectTo({
          url: '/pages/nav/nav',
        })
      },
      error: function (xhr, type, status) {
        console.log(type)
      }
    })
  },
  requestByData:function(url, data, successCallback){
    let baseUrl = hostUrl + 'report/'
    wx.request({
      url: baseUrl + url,
      method: 'POST',
      data:data,
      header: { "Authorization": "Bearer " + this.globalData.tokenId },
      success: function (res) {
        // console.log(res.data)
        if (res.data.status === 200) {
          // 成功
          successCallback(res)
        } else {
          // 错误
          // errorCallback(res)
          wx.showToast({
            title: res.data.message,
            icon: '',
            duration: 4000
          });
        }
      },
      error: function (xhr, type, status) {
        console.log(type)
      }
    })
  },
  baseInfo: function (url, successCallback, callBack){
    wx.request({
      url: hostUrl + url,
      method: 'POST',
      header: { "Authorization": "Bearer " + this.globalData.tokenId },
      success: function (res) {
        // console.log(res.data)
        if (res.data.status === 200) {
          // 成功
          successCallback(res)
        } else {
          // 错误
          // errorCallback(res)
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 4000
          });
          callBack()
        }
      },
      error: function (xhr, type, status) {
        console.log(type)
      }
    })
  },
  baseByData: function (url, data, successCallback, callBack) {
    wx.request({
      url: hostUrl + url,
      method: 'POST',
      data: data,
      header: { "Authorization": "Bearer " + this.globalData.tokenId },
      success: function (res) {
        // console.log(res.data)
        if (res.data.status === 200) {
          // 成功
          successCallback(res)
        } else {
          // 错误
          callBack(res)          
        }
      },
      error: function (xhr, type, status) {
        console.log(type)
      }
    })
  },
  requestPost: function (url, successCallback) {
    // errorCallback
    wx.request({
      url: hostUrl + 'report/' + url,
      method: 'POST',
      header: { "Authorization": "Bearer " + this.globalData.tokenId },
      success: function (res) {
        // console.log(res.data)
        if (res.data.status === 200){
          // 成功
          successCallback(res)
        } else {
          // 错误
          // errorCallback(res)
          wx.showToast({
            title: res.data.message,
            icon: '',
            duration: 4000
          });
        }
      },
      error: function(xhr, type, status){
        console.log(type)
      }
    })
  },
  globalData: {
    userInfo: null,
    tokenId: '',
    companyId: null,
    companys: []
  }
})